package com.hw.core.system.service;

import com.hw.core.system.entity.Permission;
import com.hw.core.system.entity.Role;
import com.hw.core.system.repository.PermissionRepository;
import com.hw.core.system.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Transactional(readOnly = true)//全部方法只读事务
@CacheConfig(cacheNames = "permission")
@Service
public class PermissionService {
    @Autowired
    private PermissionRepository permissionRepository;
    @Autowired
    private RoleRepository roleRepository;

    @Cacheable(key = "'list'")
    public List<Permission> findAll() {
        return permissionRepository.findAll();
    }

    @Transactional
    @CacheEvict(allEntries = true)
    public Permission add(Permission permission) {
        return permissionRepository.save( permission );
    }

    @Cacheable(key = "#id+'obj'")
    public Permission getPermissionById(Integer id) {
        return permissionRepository.findOne( id );
    }

    @Transactional
    @CacheEvict(allEntries = true)
    public void update(Permission permission) {
        Permission one = permissionRepository.findOne( permission.getId() );
        one.setName( permission.getName() );
        one.setDescription( permission.getDescription() );
    }

    @Transactional
    @CacheEvict(allEntries = true)
    public void delete(Integer id) {
        permissionRepository.delete( id );
    }

    @Cacheable(key = "#id+'list'")
    public List<Permission> findPermissionsNotInRoleId(Integer id) {
        Role one = roleRepository.findOne( id );
        List<Integer> list = new ArrayList<>();
        List<Permission> permissions = one.getPermissions();
        for (Permission permission : permissions) {
            list.add( permission.getId() );
        }

        if (list.size() > 0) {
            return permissionRepository.findPermissionByIdNotIn( list );
        } else {
            return permissionRepository.findAll();
        }

    }
}
